package com.tony.boot.control;

import com.tony.boot.entity.Author;
import com.tony.boot.repository.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.List;

@RestController
@RequestMapping(path = "/author")
public class AuthorControl {
    @Autowired
    private AuthorRepository authorRepository;

    @RequestMapping(path = "/add", method = RequestMethod.POST)
    public @ResponseBody Author addAuthor(@RequestBody Author pAuthor){
        return authorRepository.save(pAuthor);
    }
    @RequestMapping(path = "/addAll", method = RequestMethod.POST)
    public @ResponseBody List<Author> addAuthors(@RequestBody List<Author> pAuthors){
        return authorRepository.saveAll(pAuthors);
    }
    @RequestMapping(path = "/delete", method = RequestMethod.DELETE)
    public String delete(){
        authorRepository.deleteAll();
        return "delete";
    }
    @RequestMapping(path = "/deleteById/{id}", method = RequestMethod.DELETE)
    public String deleteById(@PathVariable(name = "id") Integer id){
        authorRepository.deleteById(id);
        return  "deleted id = " + id;
    }

    @RequestMapping(path = "/update", method = RequestMethod.POST)
    public @ResponseBody Object update(@RequestBody Author pAuthor){
        Author author = authorRepository.findById(pAuthor.getId()).orElse(null);
        if (author == null){
            return "no this author, name : " + pAuthor.getName();
        } else {
            return authorRepository.save(pAuthor);
        }
    }

    @RequestMapping(path = "/find",method = RequestMethod.GET)
    public  @ResponseBody List<Author> find(){
        return authorRepository.findAll();
    }
    @RequestMapping(path = "/findById/{id}",method = RequestMethod.GET)
    public  @ResponseBody Author findById(@PathVariable(name = "id") Integer id){
        return authorRepository.findById(id).get();
    }

}
